<script setup lang="ts">
import { computed, ref } from "vue";
import { Button, ClButton } from "@chulei-ui/components";
import { ElTreeV2 } from "@chulei-ui/element-plus";
import { useElementSize } from "@vueuse/core";
import type { Role } from "../../repositories/role/entity";
import type { Asset } from "../../repositories/assets/entity";
import type { AssetsLocation } from "~pages/assets/use-assets";
import type { UniverseType } from "../../sde/entity/UniverseType";
import { useAssets } from "~pages/assets/use-assets";
import { AuthRoleSelect } from "~pages/select";
import UniverseTypeIcon from "~components/universe-type/UniverseTypeIcon.vue";

const { fetch } = useAssets();
const target = ref<HTMLElement>();
const assets = ref<AssetsLocation[]>([]);
const treeRef = ref<InstanceType<typeof ElTreeV2>>();
const search = ref<string>();
const searchLocationFlag = ref(["Hangar", "Unlocked", "Cargo", "Slot", "DroneBay"]);
const { height } = useElementSize(target);
const fetchPlayerAssets = async () => {
  assets.value = await fetch(playerId.value!);
};

interface FormattedAsset {
  id: number;
  typeId?: number;
  label?: string;
  quantity: number;
  location_flag: string;
  location_type: string;
  type?: UniverseType;
  role: Role;
  children?: FormattedAsset[];
}

function formatAssets(assets: Asset[]): FormattedAsset[] {
  return assets.flatMap((asset: Asset) => {
    // 如果类型存在，正常格式化
    const formatted: FormattedAsset = {
      id: asset.item_id,
      label: asset.name ?? asset.type?.name,
      type: asset.type,
      typeId: asset.type_id,
      quantity: asset.quantity,
      location_flag: asset.location_flag,
      location_type: asset.location_type,
      role: asset.role,
    };
    if (asset.children && asset.children.length > 0) {
      formatted.children = formatAssets(asset.children);
    }

    return [formatted];
  });
}

const treeData = computed(() => {
  return assets.value
    .map((location) => {
      return {
        id: location.id,
        label: location.name,
        children: formatAssets(location.assets),
      };
    })
    .sort((a, b) => a.label.localeCompare(b.label));
});

const onSearch = (query?: string) => {
  treeRef.value!.filter(query ?? "");
};

const filterType = (query: string, node: any) => {
  return (
    //@ts-ignore
    (searchLocationFlag.value.includes(node.location_flag) || searchLocationFlag.value.length === 0) &&
    //@ts-ignore
    (node.label?.includes(query) || node.type?.name?.includes(query))
  );
};
const playerId = ref<number[]>();
</script>

<template>
  <div ref="target" class="flex flex-col h-full">
    <el-space>
      <AuthRoleSelect v-model="playerId" multiple />
      <el-input v-model="search" placeholder="请输入搜索条件" @input="onSearch" />
      <el-select v-model="searchLocationFlag" multiple placeholder="搜索位置" @change="() => onSearch(search)">
        <el-option value="Hangar" label="机库" />
        <el-option value="Unlocked" label="货柜" />
        <el-option value="Cargo" label="舰船货柜仓" />
        <el-option value="Slot" label="舰船装配" />
        <el-option value="DroneBay" label="无人机挂仓" />
      </el-select>
      <cl-button :type="Button.Type.primary" :disabled="!playerId || playerId.length === 0" @click="fetchPlayerAssets"
        >刷新</cl-button
      >
    </el-space>
    <el-tree-v2 ref="treeRef" :filter-method="filterType" :data="treeData" :height="height - 50">
      <template #default="{ data }">
        <div class="w-full flex justify-between">
          <div class="flex items-center space-x-2">
            <UniverseTypeIcon v-if="data.typeId" :id="data.typeId === 60 ? 17366 : data.typeId" />
            {{ data.label }} <span v-if="data.quantity > 1">({{ data.quantity }})</span>
          </div>
          <el-tag v-if="data.role" disable-transitions :size="'small'">{{ data.role.name }}</el-tag>
        </div>
      </template>
    </el-tree-v2>
  </div>
</template>

<style scoped lang="scss"></style>
